package controller;

import com.alibaba.fastjson.JSONObject;
import entity.UserEntity;
import ex.MyException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by john on 2016/4/24.
 */
public class BaseController<T> {
    protected static final String SESSION_USER_KEY = "user";
    private Class<T> entityClass;

    public BaseController(){
        //region 获得泛型的类型
        try {
            Type genType = getClass().getGenericSuperclass();
            Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
            entityClass = (Class) params[0];
        }catch (Exception ex){

        }
    }

    protected UserEntity getCurSessionUser(HttpSession session){
        Object userEntityObj = session.getAttribute(SESSION_USER_KEY);
        if(userEntityObj == null){
            throw new MyException("user not login");
        }
        UserEntity userEntity = (UserEntity)session.getAttribute(SESSION_USER_KEY);
        return userEntity;
    }

    protected T requestEntity(HttpServletRequest request){
        String modelStr = request.getParameter("model");
        return JSONObject.parseObject(modelStr,entityClass);
    }

}
